#!user/bin/env python3
# -*- coding:utf-8 -*-
# Email 23198899766@QQ.com
# Time : 2021/3/9 16:45

import requests
from lxml import  etree
from PIL import Image
import pytesseract


# 获取登录页面HTML代码
def html(session):
    url = 'https://so.gushiwen.cn/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx'
    page_text = session.get(url=url,headers=headers).text
    # 解析验证码图片img中的src属性值
    return etree.HTML(page_text)
# 将验证码下载到本地
def dowloud(session):
    tree= html(session)
    code_img_src='https://so.gushiwen.cn'+tree.xpath('//img[@id="imgCode"]/@src')[0]
    img_data = session.get(url=code_img_src,headers=headers).content
    # 将验证保存到本地
    with open('./code.png','wb') as fp:
        fp.write(img_data)
# 识别验证码
def distinguish():

    # 打开图片
    img=Image.open('./code.png')
    # 转化为灰度图片
    img = img.convert('L')
    # 显示
    # img.show()
    # 二进制处理
    threshold = 140
    table = []
    for i in range(256):
        if i < threshold:
            table.append(0)
        else:
            table.append(1)
    out = img.point(table,'1')
    # out.show()
    # exit()
    img = img.convert('RGB')
    # 识别图片
    pytesseract.pytesseract.tesseract_cmd = r'D:\tesseract\Tesseract-OCR\tesseract.exe'
    return pytesseract.image_to_string(img)

# 登录
def login(session):
    tree = html(session)
    viewe=tree.xpath('//*[@id="__VIEWSTATE"]/@value')[0]
    viewr=tree.xpath('//*[@id="__VIEWSTATEGENERATOR"]/@value')[0]
    url='https://so.gushiwen.cn/user/login.aspx?from=http%3a%2f%2fso.gushiwen.cn%2fuser%2fcollect.aspx'
    # 请注意下面的方法会有换行符
    img_text = distinguish().replace("\n","")
    print(img_text)
    data={
        '__VIEWSTATE': viewe,
        '__VIEWSTATEGENERATOR': viewr,
        'from':'http://so.gushiwen.cn/user/collect.aspx',
        'email': '2319899766@qq.com',
        'pwd': '123456',
        'code': img_text,
        'denglu': '登录',
    }

    login_page_text = session.post(url=url,headers=headers,data=data)
    print(login_page_text)
    # return (login_page_text.status_code) #上面一行的.text删掉，测试提交是否成功  200

    # 这是对的写法，下载登陆后的页面
    urls = 'https://so.gushiwen.cn/user/collect.aspx'
    login_text = session.get(url=urls, headers=headers).text
    with open('gushi.html', 'w', encoding='utf-8') as fp:
        fp.write(login_text)



if __name__ == '__main__':
    # 创建会话
    session = requests.Session()
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36'
    }
    dowloud(session)
    distinguish()
    login(session)



